#include <iostream>
#include <QSqlRecord>
#include <QSqlTableModel>

#include "mainwindow.h"
#include "ui_mainwindow.h"
using namespace std;

MainWindow::MainWindow(QWidget *parent): QMainWindow(parent)
{    
    setupUi(this);

    connect(tableView->horizontalHeader(), SIGNAL(sectionClicked(int)),
            this, SLOT(tableClicked(int)));
    //connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)),
    //        this, SLOT(tableResized(int,int,int)));
    //connect(tableView->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
     //           this, SLOT(dataChanged(QModelIndex,QModelIndex)));

    createToolbar();

    model = new QSqlQueryModel;
    db = new DbPage;
    searchFirst();
}

void MainWindow::tableResized( int logicalIndex, int oldSize, int newSize )
{
   adjustTableSize();
}
void MainWindow::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
    adjustTableSize();
}
void MainWindow::adjustTableSize()
{
    int width = 0;
    for(int i=0;i<tableView->model()->columnCount();i++){
        tableView->resizeColumnToContents(i);
        width += tableView->columnWidth(i);
    }
    //tableView->horizontalHeader()->resizeSection(
    //        tableView->model()->columnCount()-1,QHeaderView::Stretch);
    //QRect rect = tableView->geometry();
    //rect.setWidth(2  + width);
    //tableView->setGeometry(rect);
}

void MainWindow::createToolbar()
{
    firstAct = new QAction(QIcon(":/images/first.png"), tr("&First"), this);
    firstAct->setStatusTip(tr("Go to first page"));
    connect(firstAct, SIGNAL(triggered()), this, SLOT(searchFirst()));

    previousAct = new QAction(QIcon(":/images/previous.png"), tr("&Previous"), this);
    previousAct->setStatusTip(tr("Go to previous page"));
    connect(previousAct, SIGNAL(triggered()), this, SLOT(searchPrevious()));

    nextAct = new QAction(QIcon(":/images/next.png"), tr("&Next"), this);
    nextAct->setStatusTip(tr("Go to next page"));
    connect(nextAct, SIGNAL(triggered()), this, SLOT(searchNext()));

    lastAct = new QAction(QIcon(":/images/last.png"), tr("&Last"), this);
    lastAct->setStatusTip(tr("Go to last page"));
    connect(lastAct, SIGNAL(triggered()), this, SLOT(searchLast()));

    searchAct = new QAction(QIcon(":/images/search.png"), tr("&Search"), this);
    searchAct->setStatusTip(tr("Search"));
    connect(searchAct, SIGNAL(triggered()), this, SLOT(searchFirst()));

    addAct = new QAction(QIcon(":/images/add.png"), tr("&Add"), this);
    addAct->setStatusTip(tr("Add"));
    connect(addAct, SIGNAL(triggered()), this, SLOT(add()));

    searchText = new QLineEdit;
    connect(searchText, SIGNAL(returnPressed()),this, SLOT(searchFirst()));

    QWidget *search = new QWidget;
    QHBoxLayout *hbox1 = new QHBoxLayout;
    hbox1->addWidget(searchText);
    search->setLayout(hbox1);

    QWidget *strech = new QWidget;
    QHBoxLayout *hbox2 = new QHBoxLayout;
    hbox2->addStretch();
    strech->setLayout(hbox2);

    mainToolBar->addWidget(search);
    mainToolBar->addAction(searchAct);
    mainToolBar->addAction(addAct);
    mainToolBar->addWidget(strech);
    mainToolBar->addAction(firstAct);
    mainToolBar->addAction(previousAct);
    lblResults = new QLabel("Results");
    mainToolBar->addWidget(lblResults);
    mainToolBar->addAction(nextAct);
    mainToolBar->addAction(lastAct);

}
void MainWindow::searchFirst()
{
    search(1);
}
void MainWindow::searchPrevious()
{
    search(db->previousPage());
}
void MainWindow::searchNext()
{
    search(db->nextPage());
}
void MainWindow::searchLast()
{
    search(db->lastPage());
}
void MainWindow::add()
{
    statusBar1->showMessage("Not implemented yet ;)");

}


void MainWindow::search(int page)
{
    time.start();
    model = db->search(searchText->text(),page,orderBySql);
    tableView->setModel(model);
    tableView->resizeRowsToContents();
    //tableView->resizeColumnsToContents();
    tableView->setSortingEnabled(true);
    tableView->horizontalHeader()->setStretchLastSection(true);
    tableView->horizontalHeader()->resizeMode(QHeaderView::Interactive);
    tableView->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
    setResults();
}

void MainWindow::tableClicked(int index)
{
    orderBySql = db->columnList[index] +" "+
              (tableView->horizontalHeader()->sortIndicatorOrder()?"asc":"desc");
    searchFirst();
}

void MainWindow::setResults()
{
    lblResults->setText(QString::number(db->first) + "-"+
                        QString::number(db->last) + "/" +
                        QString::number(db->total));
    if(db->last==0)
         lblResults->setText("No results");
    if (searchText->text() != "")
        lblResults->setText(lblResults->text()+" (Filtered)");
    firstAct->setEnabled(db->firstOk());
    previousAct->setEnabled(db->previousOk());
    nextAct->setEnabled(db->nextOk());
    lastAct->setEnabled(db->lastOk());

    statusBar1->showMessage(QString::number(time.elapsed()));
}

void MainWindow::on_actionQuit_triggered()
{
    statusBar1->showMessage("Quit");

}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::information(this,"Data Viewer 1.0",
                             "DataViewer 1.0 Qt/C++ version.");
}
